package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.common.PageResult;
import com.heima.mapper.PartnerMapper;
import com.heima.pojo.Partner;
import com.heima.pojo.dto.PartnerDTO;
import com.heima.pojo.vo.PartnerVO;
import com.heima.service.PartnerService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PartnerServiceImpl implements PartnerService {
    @Autowired
    PartnerMapper partnerMapper;
    @Override
    public Boolean savePartner(PartnerDTO partnerDTO) {
        //补全信息
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDTO, partner);
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());
        //用MID5生成新的密码
        partner.setPassword(DigestUtils.md5Hex(partner.getPassword()));
        partnerMapper.savePartner(partner);
        return (Long.valueOf(partner.getId()) > 0);
    }

    @Override
    public PageResult<PartnerVO> page(PartnerDTO partnerDTO) {
        //利用pageHelper分页查询
        //1. 设置分页参数
        PageHelper.startPage(partnerDTO.getPageIndex(), partnerDTO.getPageSize());
        //2. 查询数据
        List<PartnerVO> partnerList = partnerMapper.page(partnerDTO);
        //3.封装数据
        Page page = (Page) partnerList;
        PageResult<PartnerVO> pageResult = new PageResult<>();
        pageResult.setPageIndex(partnerDTO.getPageIndex());
        pageResult.setPageSize(partnerDTO.getPageSize());
        pageResult.setTotalCount(page.getTotal());
        pageResult.setTotalPage(page.getPages());
        pageResult.setCurrentPageRecords(page.getResult());
        return pageResult;
    }

    @Override
    public PartnerVO getById(Integer id) {
        return partnerMapper.getById(id);
    }

    @Override
    public Boolean update(Long id, PartnerDTO partnerDTO) {
        Partner partner = new Partner();
        BeanUtils.copyProperties(partnerDTO, partner);
        partner.setId(id);
        partner.setUpdateTime(LocalDateTime.now());
        return partnerMapper.update(partner) > 0;
    }

    @Override
    public Boolean delete(Long id) {
        return partnerMapper.delete(id) > 0;
    }
}
